<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="zheng_tops">
        <n-button type="primary" @click="newContent"> 新建 </n-button>
        <n-button type="error" @click="deleContent" style="margin-left: 10px"> 批量删除 </n-button>
        <div class="searchs">
          <n-input
            placeholder="搜索角色名称"
            style="width: 270px; margin-left: 10px"
            v-model:value="inputValue"
          >
            <template #prefix>
              <n-icon :component="FlashOutline" />
            </template>
          </n-input>
          <n-button type="primary" @click="search" style="margin-left: 5px"> 搜索 </n-button>
        </div>
        <n-button type="warning" style="margin-left: 20px" @click="reset">重置</n-button>
      </div>
      <div style="height: 20px"></div>
      <n-data-table
        striped
        :columns="columns"
        :data="data.data"
        :pagination="pagination"
        :row-key="rowKey"
        :align="right"
        @update:checked-row-keys="handleCheck"
      />
    </n-card>
    <!-- 详情 -->
    <n-modal
      v-model:show="data.detail"
      :mask-closable="false"
      :on-after-leave="modelClose"
      preset="dialog"
      title="详情"
    >
      <div>
        <n-form
          ref="formRef"
          :model="tableDate"
          :rules="rules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-tree
            block-line
            cascade
            checkable
            :data="data.treedata"
            :checked-keys="data.checked"
            :default-expanded-keys="defaultExpandedKeys2"
            :default-checked-keys="defaultCheckedKeys2"
            @update:checked-keys="updateCheckedKeys2"
          />
        </n-form>
      </div>
    </n-modal>
    <!-- 编辑 -->
    <n-modal
      v-model:show="showModals"
      :mask-closable="false"
      :on-after-leave="modelClose"
      preset="dialog"
      title="编辑"
    >
      <div>
        <n-form
          ref="formRef"
          :model="tableDate"
          :rules="rules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-form-item label="角色名称" path="name">
            <n-input v-model:value="tableDate.name" placeholder="请输入角色名称" />
          </n-form-item>
          <n-tree
            block-line
            cascade
            checkable
            :data="data.treedata"
            :checked-keys="data.checked"
            :default-expanded-keys="defaultExpandedKeys1"
            :default-checked-keys="defaultCheckedKeys1"
            @update:checked-keys="updateCheckedKeys1"
          />
          <div style="display: flex; justify-content: flex-end">
            <n-button round type="primary" @click="handleValidateButtonClick"> 保存 </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
    <!-- 新建 -->
    <n-modal v-model:show="showNew" :mask-closable="false" preset="dialog" title="新建">
      <div>
        <n-form
          ref="formRefs"
          :model="newModel"
          :rules="newRules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-form-item label="角色名称" path="name">
            <n-input v-model:value="newModel.name" placeholder="请输入角色名称" />
          </n-form-item>
          <n-tree
            block-line
            cascade
            checkable
            :data="data.treedata"
            :default-expanded-keys="defaultExpandedKeys"
            :default-checked-keys="defaultCheckedKeys"
            @update:checked-keys="updateCheckedKeys"
          />
          <div style="display: flex; justify-content: flex-end">
            <n-button round type="primary" @click="handleValidateButtonClicks"> 确认 </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
  </div>
</template>
<script>
  import { h, ref, defineComponent, getCurrentInstance, reactive } from 'vue';
  import { useMessage, NButton, useDialog } from 'naive-ui';
  import { FlashOutline } from '@vicons/ionicons5';
  const createColumns = ({ edite, dele, play }) => {
    return [
      {
        type: 'selection',
      },
      {
        title: 'ID',
        key: 'id',
      },
      {
        title: '角色名称',
        key: 'name',
      },
      {
        title: '权限列表',
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'info',
              onClick: () => play(row),
            },
            { default: () => '详情' }
          );
        },
      },
      {
        title: '操作',
        width: 80,
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'info',
              onClick: () => edite(row),
            },
            { default: () => '编辑' }
          );
        },
      },
      {
        key: 'actions',
        width: 80,
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => dele(row),
            },
            { default: () => '删除' }
          );
        },
      },
    ];
  };

  export default defineComponent({
    setup() {
      const message = useMessage();
      const showModals = ref(false);
      const showNew = ref(false);
      const showModalRef = ref(false);
      const checkedRowKeysRef = ref([]);
      const formRef = ref(null);
      const formRefs = ref(null);
      const tableDate = ref({});
      const dialog = useDialog();
      const inputValue = ref('');
      const checkKey = ref([]);
      const newModel = reactive({
        id: '',
        name: '',
        roles: '',
      });
      const data = reactive({
        data1: [],
        iddata: [],
        treedata: [],
        checked: [],
        arr: [],
        data: [],
        search: [],
        alldata: [],
        detail: false,
      });
      let { proxy } = getCurrentInstance();
      const paginationReactive = reactive({
        page: 1,
        pageSize: 5,
        showSizePicker: true,
        pageSizes: [3, 5, 7],
        onChange: (page) => {
          paginationReactive.page = page;
        },
        onUpdatePageSize: (pageSize) => {
          paginationReactive.pageSize = pageSize;
          paginationReactive.page = 1;
        },
      });
      function lists() {
        // 权限菜单
        proxy
          .$axios({
            url: '/api/role/menu/index',
            method: 'post',
            data: {
              admin_id: 1,
              admin_name: '张三',
            },
          })
          .then((res) => {
            console.log(res);
            for (let i = 0; i < res.data.data.list.length; i++) {
              res.data.data.list[i].label = res.data.data.list[i].title;
              res.data.data.list[i].key = res.data.data.list[i].id;
            }
            data.data1 = res.data.data.list;
            data.treedata = (function makeTreeData(arr, pid) {
              let temp = [];
              for (let i = 0; i < arr.length; i++) {
                if (arr[i].pid === pid) {
                  temp.push(arr[i]);
                  arr[i].children = makeTreeData(res.data.data.list, arr[i].id);
                }
              }
              return temp;
            })(res.data.data.list, 0);
            console.log(data.treedata);
          });
        // 角色列表
        proxy
          .$axios({
            url: '/api/role/role/index', //列表数据
            method: 'post',
            data: {
              admin_id: 1,
              admin_name: '张三',
            },
          })
          .then((res) => {
            console.log(res.data.data.list);
            data.data = res.data.data.list;
            data.alldata = res.data.data.list;
          });
      }
      lists();
      //点击新建
      const newContent = () => {
        showNew.value = true;
      };
      //批量删除
      const deleContent = () => {
        console.log(checkKey.value.join(','));
        proxy
          .$axios({
            url: '/api/role/role/del',
            method: 'post',
            data: {
              id: checkKey.value,
              admin_id: 111,
              admin_name: '张',
            },
          })
          .then((res) => {
            console.log(res.data);
            if (res.data.code == 1) {
              message.success('删除成功');
              lists();
            }
          });
      };
      // 搜索
      function search() {
        data.search = [];
        console.log(inputValue.value);
        for (let j = 0; j < data.alldata.length; j++) {
          if (data.alldata[j].name.indexOf(inputValue.value) != -1) {
            data.search.push(data.alldata[j]);
          }
        }
        data.data = data.search;
      }
      function reset() {
        lists();
        inputValue.value = '';
      }
      return {
        reset,
        data,
        FlashOutline,
        newContent,
        showNew,
        formRef,
        formRefs,
        tableDate,
        inputValue,
        checkKey,
        deleContent,
        search,
        // 详情复选框
        defaultExpandedKeys2: ref([]),
        defaultCheckedKeys2: ref([]),
        updateCheckedKeys2: (v) => {
          console.log(v);
          data.iddata = v;
        },
        // 新建复选框选择
        defaultExpandedKeys: ref([]),
        defaultCheckedKeys: ref([]),
        updateCheckedKeys: (v) => {
          console.log(v);
          data.iddata = v;
        },
        // 编辑复选
        defaultExpandedKeys1: ref([]),
        defaultCheckedKeys1: ref([]),
        updateCheckedKeys1: (v) => {
          console.log(v);
          data.iddata = v;
          data.checked = v;
        },
        columns: createColumns({
          edite(row) {
            tableDate.value = row;
            data.checked = row.role.split(',').map((item) => {
              return Number(item);
            });
            showModals.value = true;
          },
          play(row) {
            console.log(row);
            tableDate.value = row;
            data.checked = row.role.split(',').map((item) => {
              return Number(item);
            });
            data.detail = true;
          },
          dele(row) {
            console.log(row.id);
            dialog.warning({
              title: '删除',
              content: '你确定要删除吗？',
              positiveText: '确定',
              negativeText: '不确定',
              onPositiveClick: () => {
                proxy
                  .$axios({
                    url: '/api/role/role/del',
                    method: 'post',
                    data: {
                      id: row.id,
                      admin_id: 11,
                      admin_name: '张',
                    },
                  })
                  .then((res) => {
                    console.log(res.data);
                    if (res.code == 1) {
                      message.success('删除成功');
                      lists();
                    }
                  });
              },
              onNegativeClick: () => {},
            });
          },
        }),
        checkedRowKeys: checkedRowKeysRef,
        pagination: paginationReactive,
        rowKey: (row) => row.id,
        handleCheck(rowKeys) {
          checkKey.value = rowKeys;
        },
        // 编辑弹窗
        showModals,
        showModal: showModalRef,
        newModel,
        rules: {
          id: {
            required: true,
            trigger: ['blur', 'change'],
            message: '请输入内容',
          },
          name: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          roles: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
        },
        newRules: {
          name: {
            required: true,
            trigger: ['blur', 'change'],
            message: '请选择内容',
          },
          roles: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
        },
        //确认编辑
        handleValidateButtonClick(e) {
          e.preventDefault();
          formRef.value?.validate((errors) => {
            if (!errors) {
              console.log(tableDate.value.id);
              console.log(tableDate.value.name);
              console.log(data.checked.join(','));
              proxy
                .$axios({
                  url: '/api/role/role/edit',
                  method: 'post',
                  data: {
                    id: tableDate.value.id,
                    name: tableDate.value.name,
                    role: data.checked.join(','),
                    admin_id: 1,
                    admin_name: '张三',
                  },
                })
                .then((res) => {
                  console.log(res);
                  if (res.data.code == 1) {
                    message.success('编辑成功');
                    lists();
                    showModals.value = false;
                  } else {
                    message.error('编辑失败');
                  }
                });
            } else {
              console.log(errors);
              message.error('编辑失败');
            }
          });
        },
        handleValidateButtonClicks(e) {
          e.preventDefault();
          formRefs.value?.validate((errors) => {
            if (!errors) {
              console.log(data.iddata.join(','));
              console.log(newModel.name);
              proxy
                .$axios({
                  url: '/api/role/role/add',
                  method: 'post',
                  data: {
                    role: data.iddata.join(','),
                    name: newModel.name,
                    admin_id: 1,
                    admin_name: '张三',
                  },
                })
                .then((res) => {
                  console.log(res);
                  if (res.data.code == 1) {
                    message.success('添加成功');
                    newModel.roles = '';
                    newModel.name = '';
                    showNew.value = false;
                    lists();
                  }
                });
            } else {
              console.log(errors);
              message.error('添加失败');
            }
          });
        },
      };
    },
  });
</script>
<style scoped>
  .win_input {
    width: 100%;
    padding: 5px;
  }
  .win_input label {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 5%;
  }
  .win_input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    border: 1px solid rgb(189, 187, 187);
    border-radius: 5px;
    outline-color: #8ebbee;
  }
  .win_input input:focus {
    box-shadow: 1px 1px 3px #4098fc;
    border: none;
  }
  .win_input input:hover {
    border: 1px solid #4098fc;
  }
  .win_input p {
    width: 60px;
    text-align: end;
  }
  .zheng_tops {
    width: 100%;
    display: flex;
  }
  .searchs {
    width: 27%;
    display: flex;
    justify-content: space-around;
  }
</style>
